(function(window){
	const PENDING = "pending";
	const FULFILLED = "fulfilled";
	const REJECTED = "rejected";
	const Promise = function(executor){
		this.state = PENDING;
		this.result = undefined;
		this.callback = [];
		const _resolved = function(value){
			if(this.state !== PENDING) return;
			// 将状态更改为成功
			this.state = FULFILLED;
			// 接收的值为成功值
			this.result = value
			// 判断是否有成功回调
			this.callback.forEach((item)=>{
				item.onResolved();
			})
		}
		const _rejected = function(value){
			if(this.state !== PENDING) return;
			// 将状态更改为失败
			this.state = REJECTED;
			// 将失败值设置为value的值
			this.result = value;
			// 判断是否有成功回调
			this.callback.forEach((item)=>{
				item.onRejected();
			})
		}
		try{
			// 执行器函数是同步调用的
			executor(_resolved.bind(this),_rejected.bind(this));
		}catch (err){
			_rejected.call(this,err);
		}
	}
	Object.assign(Promise.prototype,{
		// onResolved:成功回调函数
		// onRejected:失败回调函数
		then(onResolved,onRejected){
			if(!(onResolved instanceof Function)){
				onResolved = value=>value;
			}
			if(!(onRejected instanceof Function)){
				onRejected = err => {
					throw err;
				}
			}
			
			return new Promise((resolve,reject)=>{
				const _comment = function(cb){
					try{
						// value:成功回调的返回值
						const value = cb(this.result);
						// 判断是不是为Promise实例
						if(value instanceof Promise) value.then(resolve,reject);
						else resolve(value);
					}catch(err){
						// 产生异常
						reject(err);
					}
				}
				setTimeout(()=>{
					// 如果状态为失败调用失败回调，成功调用成功回调
					if(this.state === FULFILLED) _comment.call(this,onResolved);
					else if(this.state === REJECTED) _comment.call(this,onRejected);
					else if(this.state === PENDING){
						// 将要执行的回调函数进行保存。
						this.callback.push({
							onResolved:_comment.bind(this,onResolved),
							onRejected:_comment.bind(this,onRejected),
						})
					}
				})
			})
		},
		catch(onRejected){
			return this.then(undefined,onRejected)
		}
	})
	window.Promise = Promise;
})(window);
